﻿using DadayunApi.Model;
using KhtApi.BLL;
using KhtApi.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KhtMaintain
{
    public partial class FrmBomFixMaterial : Form
    {
        FormBLL bll = null;
        ReportBLL prdBll = null;
        //List<Bom> boms = null;
        List<BomPegging> bomPeggings = null;
        public FrmBomFixMaterial(AppAuthBase authBase, string baseUri)
        {
            this.bll = new FormBLL(authBase,baseUri);
            prdBll = new ReportBLL(authBase, baseUri);
            InitializeComponent();
        }

        private void FrmBomFixMaterial_Load(object sender, EventArgs e)
        {
            dgvData.AutoGenerateColumns = false;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ProductInfo product = prdBll.GetProductInfo(txtPrdCodeSearch.Text);
            
            txtCat1.Text = product.Catagory1;
            txtCat2.Text = product.Catagory2;
            txtCat3.Text = product.Catagory3;
            txtItemCode.Text = txtPrdCodeSearch.Text;
            txtName.Text = product.Name;
            txtModelNo.Text = product.ModelNo;
            txtSpec.Text = product.Spec;
            txtOringinal.Text = product.OriginCn;
            bomPeggings = bll.GetBomsByMaterial(txtItemCode.Text);
            dgvData.DataSource = null;
            dgvData.DataSource = bomPeggings;
            staInfo.Text = "搜索到" + bomPeggings.Count + "条BOM";
            MarkErrors();
        }

        /// <summary>
        /// 标识BOM单中产品信息与产品信息表不相符的BOM单，并用红色标识出来
        /// </summary>
        private void MarkErrors()
        {
            for (int i = 0; i < dgvData.Rows.Count; i++)
            {
                bool mark = false;                
                BomPegging b = bomPeggings.Find(bp => bp.BomId == dgvData.Rows[i].Cells["BomId"].Value.ToString());
                if (b.MatModelNo != txtModelNo.Text) mark = true;
                if (b.MatName != txtName.Text) mark = true;
                if (b.MatSpec != txtSpec.Text) mark = true;
                
                if (mark)
                {
                    dgvData.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                }
            }
            staInfo.Text += "信息有差异的已经用红色底色标识,请选择要修复的BOM";
        }

        private void btnFixSelected_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dgvData.SelectedRows)
            {
                int sus = 0, fail = 0;
                Bom bom = bll.GetBom(r.Cells["InstanceId"].Value.ToString());
                for (int i = 0; i < bom.Materials.Count; i++)
                {
                    if(bom.Materials[i].ItemCode==txtItemCode.Text)
                    {
                        bom.Materials[i].Name = txtName.Text;
                        bom.Materials[i].ModelNo = txtModelNo.Text;
                        bom.Materials[i].Spec = txtSpec.Text;
                        bom.Materials[i].OriginCn = txtOringinal.Text;
                    }
                    
                }
                if (bll.FixBomMaterials(bom))
                {
                    sus++;
                }
                else
                {
                    fail++;
                    var ans = MessageBox.Show("系统返回的信息为：\r\n" + bll.ResponseJson + "\r\n继续修复吗？", "修复过程发生错误", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (ans == DialogResult.No) return;
                    continue;
                }
                staInfo.Text = "成功修复" + sus + "条，失败" + fail + "条";
                Application.DoEvents();
            }
            staInfo.Text += "。修复已完成！";
        }

        private void btnFixAll_Click(object sender, EventArgs e)
        {
            //提取全部BOM-->逐个BOM查询每个物料的产品信息并更新
            if (MessageBox.Show("即将更新所有BOM单的物料信息。此操作耗时较长，建议在网络空闲时段内执行此操作。确定马上执行吗？", "操作确认",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
            staInfo.Text = "正在查询全部BOM单，数据量大，请耐心等候...";Application.DoEvents();            
            var boms = bll.GetBoms();
            dgvData.Columns.Clear();
            dgvData.AutoGenerateColumns = true;
            dgvData.DataSource = null;
            dgvData.DataSource = boms;
            dgvData.MultiSelect = false;
            string msg = "查询到" + boms.Count + "条BOM";
            staInfo.Text = msg + ",马上逐条更新";
            int sus = 0, fail = 0,pass=0;
            int n = 0;
            foreach (var b in boms)
            {
                dgvData.Rows[n++].Selected = true;
                bool fix = false;
                for (int i = 0; i < b.Materials.Count; i++)
                {
                    ProductInfo p = prdBll.GetProductInfo(b.Materials[i].ItemCode);
                    //用物料编码查询物料信息，并更新以下四项
                    if (b.Materials[i].ModelNo != p.ModelNo|| b.Materials[i].Name != p.Name
                        || b.Materials[i].Spec != p.Spec|| b.Materials[i].Origin != p.Origin)
                    {
                        b.Materials[i].ModelNo = p.ModelNo;
                        b.Materials[i].Name = p.Name;
                        b.Materials[i].Spec = p.Spec;
                        b.Materials[i].Origin = p.Origin;
                        fix = true;
                    }
                   
                }
                if(fix)
                {
                    if (bll.FixBomMaterials(b))
                        sus++;
                    else
                    {
                        fail++;
                        msg = "正在修复物料代码：" + b.ItemCode + ", BOM编码：" + b.BomId;
                        msg += "\r\n系统返回的信息为：\r\n" + bll.ResponseJson;
                        msg += "\r\n继续修复吗？";
                        var ans = MessageBox.Show(msg, "修复过程发生错误", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (ans == DialogResult.No) return;
                        continue;
                    }

                    
                }
                else
                {
                    pass++;
                }
                staInfo.Text = "进度：" + n + "/" + boms.Count + "，成功修复" + sus + "条，失败" + fail + "条，跳过：" + pass + "条";
                Application.DoEvents();
            }
            staInfo.Text += "。修复完成！";
        }

        private void dgvData_SelectionChanged(object sender, EventArgs e)
        {
            btnFixSelected.Enabled = dgvData.SelectedRows.Count > 0;
        }
    }
}
